const config = {
    pageIsLoading: true,
    url: '',
    oss: '',
    timeout: 60000
}


const request = (url, data, method = 'GET', toast = true) => {
    let header = null
    let withCredentials = false
    url = config.url + url
    return new Promise((resolve, reject) => {
        uni.request({
            url,
            data,
            header,
            method,
            timeout: config.timeout,
            withCredentials,
            success: (res) => {
                if (res.statusCode === 200) {
                    let {code, msg} = res.data
                    if (code === 200) {
                        resolve(res.data)
                    } else {
                        if (toast) {
                            showToast(msg)
                        } else {
                            reject(res.data)
                        }
                    }
                } else {
                    showToast('系统错误，请联系官方！')
                }
            },
            fail: (err) => {
                console.log(err)
            }
        })
    })
}
/*
* type
*       tel：手机号
*       card： 银行卡
*       email：邮箱
*       password： 密码
*       number：正整数
*       https：url验证
* */
const regExp = (type, key) => {
    let reg = null
    if (type === "tel") reg = /^1[3-9][0-9]{9}$/; // 手机号
    if (type === 'card') reg = /^\d{16,19}$/; // 银行卡
    if (type === 'email') reg = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}/; // 邮箱
    if (type === 'password') reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w]{8,16}$/; // 密码
    if (type === 'number') reg = /^\d+$/; //整数
    if (type === 'https') reg = /^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$/; // url验证
    return reg && reg.test(key)
}

const getSystemParams = (name) => {
    let system = uni.getSystemInfoSync()
    return system[name]
}
/*
 * type
 *     bis:去重
 *     copy：深度拷贝
 *     addStart：添加到数组第一位
 *     addEnd：添加到数组最后一位
 *     concat：数组拼接
 *     del：删除（索引+1）
 *     index：获取数组相应的index
 *     activeItem：获取数组相应的数组对象
 */
const operateArray = (type, list, item, name) => {
    let reply = null
    if (type === 'bis') reply = [...new Set(list)];
    if (type === 'copy') reply = JSON.parse(JSON.stringify(list));
    if (type === 'addStart') reply = list.unshift(item)
    if (type === 'addEnd') reply = list.push(item)
    if (type === 'concat') reply = list.concat(item)
    if (type === 'del') reply = list.splice(item)
    if (type === 'index') reply = list.findIndex(iten => iten[name] === item[name])
    if (type === 'activeItem') reply = list.filter(iten => iten[name] === item[name])
    return reply
}

const getPrePage = (n = 2) => {
    let pages = getCurrentPages()
    let prePage = pages[pages.length - n]
    return prePage
}

const goPage = (url, type = null) => {
    let prePage = getPrePage()
    if (config.pageIsLoading) {
        config.pageIsLoading = false
        switch (type) {
            case 'to':
                uni.redirectTo({
                    url,
                    complete: () => {
                        config.pageIsLoading = true
                    }
                })
                break
            case 'tab':
                uni.switchTab({
                    url,
                    complete: () => {
                        config.pageIsLoading = true
                    }
                })
                break
            case 'close':
                uni.reLaunch({
                    url,
                    complete: () => {
                        config.pageIsLoading = true
                    }
                })
            case 'back':
                uni.navigateBack({
                    delta: url,
                    complete: () => {
                        config.pageIsLoading = true
                    }
                })
                break
            default:
                uni.navigateTo({
                    url,
                    complete: () => {
                        config.pageIsLoading = true
                    }
                })
                break
        }
    } else {
        if (prePage && prePage.route && page.route != url) {
            config.pageIsLoading = true
            goPage(url, type)
        }
    }
}

const formatDate = (time, fmt = '-') => {
    let ret
    let date = date ? date * 1000 : new Date()
    const obj = {
        'Y+': date.getFullYear(),
        'M+': date.getMonth() + 1,
        'D+': date.getDate(),
        'H+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in obj) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        }
    }
    return fmt;
}

const showToast = (title, icon = 'none', duration = 2000) => {
    uni.showToast({
        title,
        icon,
        duration
    })
}

const getImageURL = (url) => {
    let is = regExp('https', url)
    if (is) {
        return url
    } else {
        return config.oss + url
    }
}

const callPhone = (phoneNumber) => {
    uni.makePhoneCall({
        phoneNumber
    })
}

const scrollTo = (scrollTop, duration = 300, selector = null) => {
    return new Promise(resolve => {
        uni.pageScrollTo({
            scrollTop,
            selector,
            duration,
            success: (res) => {
                resolve(res)
            }
        });
    })
}

const getDomIdClass = (that, name, type = '#') => {
    const query = uni.createSelectorQuery().in(that)
    let dom = type === '#' ? query.select('#' + name) : query.selectAll('.' + name)
    return new Promise(resolve => {
        dom.boundingClientRect(rect => {
            resolve(rect)
        }).exec()
    })
}

const updateAPP = () => {
    const updateManager = uni.getUpdateManager();
    updateManager.onCheckForUpdate(res => {
        console.log(res.hasUpdate);
    });
    updateManager.onUpdateReady(res => {
        uni.showModal({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success(res) {
                if (res.confirm) {
                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                    updateManager.applyUpdate();
                }
            }
        });

    });
    updateManager.onUpdateFailed(res=> {
        // 新的版本下载失败
    });
}


export default {
    config,
    operateArray,
    getPrePage,
    goPage,
    formatDate,
    showToast,
    getImageURL,
    callPhone,
    scrollTo,
    getDomIdClass,
    updateAPP,

}